package com.example.siyun.handle;

import com.google.code.kaptcha.Constants;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.thymeleaf.util.StringUtils;

import javax.print.attribute.standard.PresentationDirection;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: 全
 * @Date: 2022/10/10 15:17
 * @Description:自定义验证码的过滤器
 */
public class CodeFilter extends HttpFilter {


    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        String uri = req.getServletPath();
        if (uri.equals("/goLogin") && req.getMethod().equalsIgnoreCase("post")) {
            // 服务端生成的验证码数据
            String sessionCode = (String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            // 用户输入的验证码数据
            String formCode = req.getParameter("captcha").trim();
            if (StringUtils.isEmpty(formCode)) {
                res.sendRedirect("/hello" + "?err");
            }else if (sessionCode.equals(formCode)) {
                System.out.println("验证通过");
            } else {
//                throw new AuthenticationServiceException("验证码输入不正确");
                res.sendRedirect("/hello" + "?err");
            }
        }
        chain.doFilter(req, res);
    }
}
